package com.beijiteshop.shop.ui.detail

import android.content.Context
import android.os.Bundle
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.beijiteshop.libcommon.base.adapter.showEmpty
import com.beijiteshop.libcommon.base.adapter.showError
import com.beijiteshop.libcommon.base.adapter.showLoading
import com.beijiteshop.libcommon.base.adapter.showNetError
import com.beijiteshop.libcommon.ext.databinding.bindView
import com.beijiteshop.libcommon.ext.databinding.inflateBinding
import com.beijiteshop.libcommon.handler.WeakHandler
import com.beijiteshop.libcommon.utils.DensityUtil
import com.beijiteshop.libcommon.utils.EventUtil
import com.beijiteshop.libcommon.utils.ImageLoadUtil
import com.beijiteshop.libcommon.utils.setDeleteLine
import com.beijiteshop.shop.R
import com.beijiteshop.shop.app.PageIndex
import com.beijiteshop.shop.base.BaseContainerFragment
import com.beijiteshop.shop.databinding.FragmentProductDetailBinding
import com.beijiteshop.shop.databinding.HeaderProductDetailBinding
import com.beijiteshop.shop.databinding.HeaderProductInfoBinding
import com.beijiteshop.shop.model.api.request.AddShopCarRequest
import com.beijiteshop.shop.model.api.response.ProductBean
import com.beijiteshop.shop.model.api.response.ProductDetailBean
import com.beijiteshop.shop.model.event.EventKey
import com.beijiteshop.shop.ui.detail.vm.ProductDetailVM
import com.beijiteshop.shop.ui.detail.adapter.ImageGalleryAdapter
import com.beijiteshop.shop.ui.detail.adapter.ProductDetailAdapter
import com.beijiteshop.shop.ui.detail.fragment.SpecsSelectionDialog
import com.beijiteshop.shop.ui.order.fragment.OrderConfirmFragment
import com.beijiteshop.shop.ui.shopcar.vm.ShopCarVM
import com.beijiteshop.shop.utils.SpecColorUtil
import com.beijiteshop.shop.utils.TabCreateUtil
import com.blankj.utilcode.util.LogUtils
import org.koin.android.viewmodel.ext.android.viewModel

/**
 * 商品详情页面
 */
class ProductDetailFragment: BaseContainerFragment(R.layout.fragment_product_detail){

    companion object{

        const val BUNDLE_PRODUCT = "bundle_product"

        fun newInstance(productBean: ProductBean) : Fragment{
            return ProductDetailFragment().apply {
                val bundle = Bundle()
                bundle.putParcelable(BUNDLE_PRODUCT,productBean)
                arguments = bundle
            }
        }
    }

    private val mBinding: FragmentProductDetailBinding by bindView()
    private val mProductDetailVM: ProductDetailVM by viewModel()
    private val mShopCarVM: ShopCarVM by viewModel()

    private lateinit var mHeaderProductInfoBinding: HeaderProductInfoBinding
    private lateinit var mHeaderProductDetailBinding: HeaderProductDetailBinding

    private val mDetailAdapter = ProductDetailAdapter(mutableListOf())
    private var mProductBean: ProductBean? = null
    private var mProductDetailBean: ProductDetailBean? = null
    private val mScrollHandler: WeakHandler by lazy { ScrollHandler(requireContext()) }
    //列表滑动的高度
    private var mScrollHeight: Int = 0
    //是否点击了TAB
    private var mIsClickTab = false

    //顶部标题栏的高度
    private val mTitleBarHeight: Float by lazy {
        resources.getDimension(R.dimen.title_bar_height)
    }

    private val mTabTitles: Array<String> by lazy {
        resources.getStringArray(R.array.product_detail_tabs)
    }

    override fun initView(view: View) {
        mProductBean = arguments?.getParcelable(BUNDLE_PRODUCT)
        initSellOutState()
        initProductInfoHeaderView()
        initProductDetailHeaderView()
        initRV()
        initIndicator()
    }

    override fun initData() {

    }

    override fun onLazyLoad() {
        mProductBean?.let {
            mDetailAdapter.showLoading()
            mProductDetailVM.getProductDetailInfo(it.bus_GoodsID)
        }
    }

    override fun initEvent() {
        startObserve()

        //返回按钮
        mBinding.productDetailBackIv.setOnClickListener {
            close()
        }
        mBinding.productDetailBackRoundedIv.setOnClickListener {
            close()
        }

        //返回首页
        mBinding.productDetailBackHomeIv.setOnClickListener {
            EventUtil.post(EventKey.TO_HOME)
            close()
        }

        //规格选择
        mHeaderProductInfoBinding.headerProductInfoSpecsTv.setOnClickListener {
            showSpecAndColorDialog()
        }

        //规格选择
        mHeaderProductInfoBinding.headerProductInfoSpecMoreIv.setOnClickListener {
            showSpecAndColorDialog()
        }

        //加入购物车
        mBinding.productDetailAddBtn.setOnClickListener {
            if (checkIsSelectSpecOrColor()){
                if (!mProductDetailBean!!.isSaleOut()){
                    val color = mProductBean!!.color?:""
                    val spec = mProductBean!!.spec?:""
                    mShopCarVM.addToShopCar(AddShopCarRequest(mProductDetailBean!!.bus_GoodsID,color,spec))
                }
            }else{
                showSelectSpecOrColorPrompt()
            }

        }

        //购物车
        mBinding.productDetailShopCarIv.setOnClickListener {
            close()
            EventUtil.post(EventKey.TO_SHOP_CAR)
        }

        //立即购买
        mBinding.productDetailBuyBtn.setOnClickListener {
            if (checkIsSelectSpecOrColor()){
                val bundle = Bundle()
                bundle.putParcelable(OrderConfirmFragment.BUNDLE_PRODUCT,mProductBean)
                startActivity(PageIndex.ORDER_CONFIRM,bundle)
            }else{
                showSelectSpecOrColorPrompt()
            }
        }

        //刷新商品在购物车中的数量
        EventUtil.observe<Any>(this,EventKey.REFRESH_CART_NUM){
            getGoodsCountInCart()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mScrollHandler.removeCallbacksAndMessages(null)
    }

    /**
     * 初始化是否售罄的状态显示
     */
    private fun initSellOutState(){
        mProductBean?.let {
            mBinding.productDetailBuyBtnLl.visibility = if (it.sellOut()) View.GONE else View.VISIBLE
            mBinding.productDetailSaleOutFl.saleOutFl.visibility = if (it.sellOut()) View.VISIBLE else View.GONE
        }
    }

    private fun initRV(){
        mDetailAdapter.apply {
            addHeaderView(getProductInfoHeaderView())
            addHeaderView(getProductDetailHeaderView())
        }

        mBinding.productDetailRv.apply {
            itemAnimator = null
            layoutManager = LinearLayoutManager(context)
            adapter = mDetailAdapter
            addOnScrollListener(object : RecyclerView.OnScrollListener(){

                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    when(newState){
                        //滚动停止
                        RecyclerView.SCROLL_STATE_IDLE  -> {
                            if (mIsClickTab){
                                mScrollHandler.sendEmptyMessage(1)
                            }else{
                                mScrollHandler.sendEmptyMessage(0)
                            }
                        }
                    }
                }

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    mScrollHeight += dy
                    //标题栏的透明度
                    var alpha = mScrollHeight.toFloat() / DensityUtil.dp2px(context,mTitleBarHeight.toInt())
                    if (alpha > 1f) alpha = 1f
                    //标题栏
                    mBinding.productDetailTitleBarRl.alpha = alpha
                    mBinding.productDetailTitleBarRl.visibility = if (alpha > 0) View.VISIBLE else View.GONE
                    //单独的返回按钮
                    mBinding.productDetailBackRoundedIv.visibility = if (mScrollHeight > 0) View.GONE else View.VISIBLE
                    //返回首页按钮
                    mBinding.productDetailBackHomeIv.visibility = if (mScrollHeight > 0) View.GONE else View.VISIBLE
                }
            })
        }
    }

    private fun initProductInfoHeaderView(){
        mHeaderProductInfoBinding = inflateBinding<HeaderProductInfoBinding>(LayoutInflater.from(context))
    }

    private fun initProductDetailHeaderView(){
        mHeaderProductDetailBinding = inflateBinding<HeaderProductDetailBinding>(LayoutInflater.from(context))
    }

    private fun getProductInfoHeaderView() : View = mHeaderProductInfoBinding.root

    private fun getProductDetailHeaderView() : View = mHeaderProductDetailBinding.root

    private fun initIndicator(){
        TabCreateUtil.create(requireContext(),mBinding.productDetailIndicator,mTabTitles.toList()){index ->
            if (mScrollHeight != 0){
                mIsClickTab = true
                when(index){
                    //滑动到商品
                    0 -> mBinding.productDetailRv.smoothScrollToPosition(0)
                    1 -> {//滑动到商品详情
                        val y = getInfoHeight() - mScrollHeight
                        mBinding.productDetailRv.smoothScrollBy(0,y)
                    }
                    2 -> {//滑动到用户评价
                        mBinding.productDetailRv.smoothScrollToPosition(2)
                    }
                }
            }

        }
    }

    private fun startObserve(){
        mProductDetailVM.liveProductDetail.observeKt {
            mProductDetailBean = it
            mProductDetailBean?.let {detailBean ->
                setProductInfo()
                //当有多种规格时不默认选择规格，只有一种规格时才显示默认规格
                if (detailBean.specifications.isNullOrEmpty() && detailBean.colors.isNullOrEmpty()){
                    mProductBean?.spec = detailBean.specification
                }
                getGoodsCountInCart()
            }
        }

        mProductDetailVM.liveNetError.observeKt {
            mDetailAdapter.showNetError (it){
                onLazyLoad()
            }
        }

        mProductDetailVM.liveError.observeKt {
            mDetailAdapter.showError(it){
                onLazyLoad()
            }
        }

        mProductDetailVM.liveEmpty.observeKt {
            mDetailAdapter.showEmpty (it){ onLazyLoad() }
        }

        mShopCarVM.liveAddToShopCar.observeKt {result ->
            result?.let {
                val(success,msg) = it
                if (success){
                    showToastInCenter(resources.getString(R.string.added_to_cart))
                    EventUtil.post(EventKey.REFRESH_SHOP_CART)
                    getGoodsCountInCart()
                }else{
                    showToastInCenter(msg?:resources.getString(R.string.something_error))
                }
            }
        }

        //商品在购物车中的数量
        mShopCarVM.liveGoodsCount.observeKt { count->
            count?.let {
                mBinding.productDetailCarNumTv.apply {
                    visibility = View.VISIBLE
                    text = it.toString()
                }
            }
        }
    }

    /**
     * 设置商品信息
     */
    private fun setProductInfo(){
        mProductDetailBean?.let {
            mHeaderProductInfoBinding.product = it
            mHeaderProductInfoBinding.headerProductInfoMarketPriceTv.setDeleteLine()
            if (it.isSeckill()){
                mHeaderProductInfoBinding.headerProductInfoSaleTagTv.apply {
                    text = resources.getString(R.string.limited_time_grab)
                    background = ContextCompat.getDrawable(requireContext(),R.drawable.bg_product_sale_tag_red)
                }
            }
            else {
                mHeaderProductInfoBinding.headerProductInfoSaleTagTv.apply {
                    text = resources.getString(R.string.preferential_purchase)
                    background = ContextCompat.getDrawable(requireContext(),R.drawable.bg_product_sale_tag_blue)
                }
            }
            //规格、颜色
            if (!it.specifications.isNullOrEmpty() || !it.colors.isNullOrEmpty()){
                mHeaderProductInfoBinding.headerProductInfoSpecsTv.text = resources.getString(R.string.please_select_spec)
            }else {
                mHeaderProductInfoBinding.headerProductInfoSpecsTv.text = it.specification
            }

            if (!it.specifications.isNullOrEmpty() || !it.colors.isNullOrEmpty()){
                mHeaderProductInfoBinding.headerProductInfoSpecMoreIv.visibility = View.VISIBLE
            }else{
                mHeaderProductInfoBinding.headerProductInfoSpecMoreIv.visibility = View.GONE
            }


            setImageBanner(it.topImgs.toMutableList())
            setProductDetailImage(it.detailImg.toMutableList())
            mDetailAdapter.setNewInstance(mProductDetailVM.getProductDetailItemBean())
        }

    }

    /**
     * 设置图文详情的长图
     */
    private fun setProductDetailImage(urls: MutableList<String>){
        urls.forEach { url ->
            val imageView = ImageView(requireContext())
            val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT)
            imageView.layoutParams = layoutParams
            mHeaderProductDetailBinding.headerProductDetailImgsLl.addView(imageView)
            ImageLoadUtil.loadImageByWrap(url,imageView)
        }
    }

    /**
     * 设置商品图片
     */
    private fun setImageBanner(urls: MutableList<String>){
        val imageAdapter = ImageGalleryAdapter(urls)
        mHeaderProductInfoBinding.headerProductInfoVp.apply {
            addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
                override fun onPageScrollStateChanged(state: Int) {

                }

                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {

                }

                override fun onPageSelected(position: Int) {
                    mHeaderProductInfoBinding.headerProductInfoIndicatorTv.text = "${(position+1)}/${urls.size}"
                }

            })
            adapter = imageAdapter
            currentItem = 0
            mHeaderProductInfoBinding.headerProductInfoIndicatorTv.text = "1/${urls.size}"
        }
    }

    private fun getInfoHeight(): Int{
        return getProductInfoHeaderView().height
    }

    private fun getDetailHeight(): Int{
        return getProductDetailHeaderView().height
    }

    inner class ScrollHandler(context: Context) : WeakHandler(context){
        override fun handleMsg(msg: Message) {
            when(msg.what){
                0 -> {
                    //滑动停止位置在商品部分
                    if (mScrollHeight <= getInfoHeight()){
                        mBinding.productDetailIndicator.onPageSelected(0)
                    }else if (mScrollHeight in (getInfoHeight() + 1)..getInfoHeight()+getDetailHeight()){//滑动停止位置在商品详情部分
                        mBinding.productDetailIndicator.onPageSelected(1)
                    }else{//滑动停止位置在商品评价部分
                        mBinding.productDetailIndicator.onPageSelected(2)
                    }
                }

                1 -> {
                    mIsClickTab = false
                }
            }
        }

    }

    /**
     * 显示颜色和规格弹框
     */
    private fun showSpecAndColorDialog(){
        if (mProductDetailBean != null
            && mProductBean != null
            && !mProductDetailBean!!.isSaleOut()
            && ( !mProductDetailBean!!.colors.isNullOrEmpty() || !mProductDetailBean!!.specifications.isNullOrEmpty())){
            val dialog = SpecsSelectionDialog.newInstance(mProductDetailBean!!,mProductBean!!)
            dialog.show(childFragmentManager,"")
            dialog.setOnSpecColorChangeListener(object : SpecsSelectionDialog.OnSpecColorChangeListener{
                override fun onChanged(spec: String?, color: String?) {
                    LogUtils.dTag("TAG","spec:${spec},color:${color}")
                    val result = StringBuilder()
                    if (spec != null){
                        mProductBean?.spec = spec
                        result.append(spec)
                    }
                    if (color != null){
                        mProductBean?.color = color
                        result.append("·")
                        result.append(color)
                    }
                    getGoodsCountInCart()
                    mHeaderProductInfoBinding.headerProductInfoSpecsTv.text = result
                }

            })
        }
    }

    /**
     * 获取商品在购物车里的数量
     */
    private fun getGoodsCountInCart(){
        if (checkIsSelectSpecOrColor()){
            mShopCarVM.getGoodCount(mProductDetailBean!!.bus_GoodsID,mProductBean!!.color,mProductBean!!.spec!!)
        }
    }

    private fun checkIsSelectSpecOrColor(): Boolean{
        return SpecColorUtil.checkIsSelectSpecOrColor(mProductBean,mProductDetailBean)
    }

    private fun showSelectSpecOrColorPrompt(){
        showToast(resources.getString(R.string.please_select_spec_or_color))
    }
}